<?php
namespace app\controller;

use support\Request;
use think\facade\Db;
use app\model\Admin;
use app\model\AdminRole;

class Index
{
    public function index(Request $request)
    {
        return view('index/index');
    }
	
	public function login(Request $request)
	{
		$username = $request->post('username');
		$password = $request->post('password');
		
		if($username==null || $password==null){
			return return_json(0, '用户名和密码不能为空');
		}

        $modelAdmin = new Admin;
        $where['username'] = $username;
        $where['status'] = 1;
        $infoAdmin = $modelAdmin->where($where)->find();
        if (empty($infoAdmin)) {
            return return_json(0, '用户名不存在');
        }

        $new_password = md5(md5($password) . $infoAdmin['salt'] . $infoAdmin['id']);
        if ($infoAdmin['password'] != $new_password) {
            return return_json(0, '密码错误');
        }

        $token = md5(rand(100000, 999999) . time());
        $temp = array(
            'id' => $infoAdmin['id'],
            'username' => $infoAdmin['username'],
            'nickname' => $infoAdmin['nickname'],
            'token' => $token,
            'roleId' => $infoAdmin['roleId'],
            'sorttime' => time()
        );
        $modelAdmin->update($temp);
		
		//添加session
		$session = $request->session();
		$session->put($temp);
		
		//缓存组权限信息
		$modelAdminRole = new AdminRole;
		$listRole = $modelAdminRole->getList();
		cache('role_list', $listRole);
		
		$temp['url'] = url('home/index');
        return return_json(1, '登录成功', $temp);
	}
	
	/**
     * 退出登录
     */
    public function logout(Request $request){
		$request->session()->flush();
		
        return return_json(2,'退出系统成功！',url('index/index'));
    }
	
	/*
     * 一键清空缓存
     */
    public function delcache() {
        $path = '/runtime';
        delDirAndFile($path);
        return return_json(1,'缓存清除成功');
    }

}
